package com.yc.home.cloudother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.bean.Result;
import com.yc.entity.Collection;
import com.yc.entity.Question;
import com.yc.home.cloudother.mapper.CollectionMapper;
import com.yc.home.cloudother.mapper.QuestionMapper;
import com.yc.home.cloudother.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzk
 * @since 2024-09-25
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    CollectionMapper collectionMapper;

    //加入收藏
    @RequestMapping("add")
    Result add(String qid, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        Object id = user.get("id");
        String uid = id.toString();
        //首先查询添加过没
        LambdaQueryWrapper<Collection> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Collection::getQid, qid);
        lqw.eq(Collection::getUid, uid);
        Long aLong = collectionMapper.selectCount(lqw);
        if(aLong > 0){
            return new Result(0, "已加入收藏", null);
        }else{
            //插入数据
            Collection collection = new Collection();
            collection.setQid(Integer.valueOf(qid));
            collection.setUid(Integer.valueOf(uid));
            collectionMapper.insert(collection);
            return new Result(1, "加入收藏成功", null);
        }
    }

    @RequestMapping("getsum")
    Result getsum(String uid){
        LambdaQueryWrapper<Collection> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Collection::getUid, uid);
        Long aLong = collectionMapper.selectCount(lqw);
        return new Result(1, "总收藏数", aLong);
    }

    @Autowired
    QuestionMapper questionMapper;

    @RequestMapping("getqusetion")
    Page getqusetion(@RequestParam(defaultValue = "1") int page,
                     @RequestParam(defaultValue = "10") int size, String input, String uid, String start, String end){
        Page<Collection> pageObj = new Page<>(page, size);

        // 条件设置
        LambdaQueryWrapper<Collection> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Collection::getUid, uid);
        if(!"".equals(start) && !"".equals(end)){
            lqw.ge(Collection::getCreatetime, start);
            lqw.le(Collection::getCreatetime, end);
        }

        // 执行分页查询
        Page<Collection> makenoPage = collectionMapper.selectPage(pageObj, lqw);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 使用Stream API转换Doquestion为Question并更新Page对象的records
        List<cqusetion> questionList = makenoPage.getRecords().stream()
                .map(doquestion -> {
                    LambdaQueryWrapper<Question> lqw1 = new LambdaQueryWrapper<>();
                    lqw1.eq(Question::getId, doquestion.getQid());
                    lqw1.like(Question::getContent, "%"+ input +"%");
                    Question question = questionMapper.selectOne(lqw1);
                    if(question == null){
                        return null;
                    }
                    cqusetion doq = new cqusetion();
                    doq.setId(question.getId());
                    doq.setContent(question.getContent());
                    doq.setCourse(question.getCourse());
                    doq.setIdeas(question.getIdeas());
                    doq.setItems(question.getItems());
                    doq.setImage(question.getImage());
                    doq.setCreateTime(question.getCreateTime());
                    doq.setType(question.getType());
                    doq.setCid(String.valueOf(doquestion.getId()));
                    doq.setDocreate(sdf.format(doquestion.getCreatetime()));
                    return doq;
                }).filter(Objects::nonNull)
                .collect(Collectors.toList());

        //替换数据
        Page<cqusetion> questionPage = new Page<>(makenoPage.getCurrent(), makenoPage.getSize(), makenoPage.getTotal());
        questionPage.setRecords(questionList);
        return questionPage;
    }

    //删除刷题表
    @RequestMapping("del")
    Result del(String id){
        try{
            collectionMapper.deleteById(id);
            return new Result(1, "删除成功", null);
        }catch (Exception e){
            return new Result(0, "删除失败", null);
        }
    }

}
@Data
class cqusetion {
    private Integer id;

    private String content;

    private String course;

    private String type;

    private String items;

    private Timestamp createTime;

    private String ideas;

    private String image;

    private String cid;

    private String docreate;
}

